const fs = require('fs');
const multer = require('koa-multer');
const uuid = require('uuid');
const storage = multer.diskStorage({
    //文件保存路径  
    destination: function (req, file, cb) {
        cb(null, '../upload/')
    },
    //修改文件名称  
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        // console.log(`req: ${req}`);
        console.log(file);
        
        cb(null, generateId() + "." + fileFormat[fileFormat.length - 1]);
    }
})
const upload = multer({ storage: storage });

function generateId() {
    return uuid.v4();
}

function addMapping(router, mapping) {
    for (var url in mapping) {
        if (url.startsWith('GET ')) {
            var path = url.substring(4);
            router.get(path, mapping[url]);
            console.log(`register URL mapping: GET ${path}`);
        }
        else if (url.startsWith('POST ')) {
            var path = url.substring(5);
            router.post(path, mapping[url]);
            console.log(`register URL mapping: POST ${path}`);
        }
        else if (url.startsWith('POSTFILE ')) {
            var path = url.substring(9);
            router.post(path, upload.single('file'), mapping[url]);
            console.log(`register URL mapping: POST ${path}`);
        } 
        else if (url.startsWith('PUT ')) {
            var path = url.substring(4);
            router.put(path, mapping[url]);
            console.log(`register URL mapping: PUT ${path}`);
        }
        else if (url.startsWith('DELETE ')) {
            var path = url.substring(7);
            router.del(path, mapping[url]);
            console.log(`register URL mapping: DELETE ${path}`);
        }
        else {
            console.log(`invalid URL: ${url}`);
        }
    }
}

function addController(router, dir) {
    let js_files = fs.readdirSync(dir).filter((f) => {
        return f.endsWith(".js");
    });

    for (var f of js_files) {
        console.log(`process controller: ${f}...`);
        let mapping = require(dir + '/' + f);
        addMapping(router, mapping);
    }
}

module.exports = function (dir) {
    let controllers_dir = dir || __dirname,  // 如果不传参数，扫描目录默认为__dirname
        router = require('koa-router')();
    addController(router, controllers_dir);
    // addUploadFile(router);
    return router.routes();
};
